<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/11
 * Time: 12:48
 */

namespace app\common\model\mysql;


use think\Db;
use think\facade\Log;

class Admin extends BaseModel
{
    /**
     * 状态获取器
     * @param $value
     * @return string
     */
    public function getStatusAttr($value)
    {
        return $value ? "<i class='fa fa-check-circle'></i>" : "<i class='fa fa-close'></i>";
    }

    /**
     * @param $group_id
     * @param $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function saveData($group_id, $data)
    {
        $this->startTrans();
        try {
            $admin_id = $this->insertGetId($data);
            $res      = AuthGroupAccess::create(
                [
                    'uid'      => $admin_id,
                    'group_id' => $group_id,
                ]
            );
            if (!$res) {
                throw new \think\Exception("管理员表和角色表中间表插入失败");
            }
            $this->commit();

            return true;
        } catch (\Exception $e) {
            Log::record($e->getMessage());
            $this->rollback();

            return false;
        }
    }

    public function updateAdminAndGroupAccessById($id, $data, $group_id)
    {
        $this->startTrans();
        try {
            AuthGroupAccess::where('uid', $id)->update(['group_id' => $group_id]);
            $res = $this->where('id', $id)->update($data);
            if (!$res) {
                throw new \think\Exception("管理员表和角色表中间表编辑失败");
            }
            $this->commit();

            return true;
        } catch (\Exception $e) {
            Log::record($e->getMessage());
            $this->rollback();

            return false;
        }
    }

    /**
     * @param $id
     * @return bool|int
     */
    public function deleteById($id)
    {
        $id = intval($id);
        if (empty($id)) {
            return false;
        }
        Db::startTrans();
        try {
            Db::name('auth_group_access')->where('uid', $id)->delete();
            $result = $this->where('id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        return $result;
    }
}